package edu.nepu.flink.api.sql;

import edu.nepu.flink.api.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.annotation.DataTypeHint;
import org.apache.flink.table.annotation.FunctionHint;
import org.apache.flink.table.annotation.InputGroup;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.ScalarFunction;
import org.apache.flink.table.functions.TableFunction;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @Date 2024/3/5 21:45
 * @Created by chenshuaijun
 */
public class SelfDefineTableFunction {


    public static void main(String[] args) {


        /**
         *
         *  表函数的本质就是一进多出:
         *  下面我将演示自定义标量函数的过程，实现一个求传入参数hashcode值的函数
         */

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        DataStreamSource<String> sensorDS = env.fromElements(
                "hello world",
                "hello zhang san",
                "hello li si",
                "hello wangwu"
        );

        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);


        //TODO 注意这里创建的是一个临时的系统函数
        tableEnv.createTemporarySystemFunction("splitFunction",SplitFunction.class);

        Table sensorTable = tableEnv.fromDataStream(sensorDS,$("words"));

        tableEnv.createTemporaryView("sensors",sensorTable);

        tableEnv.sqlQuery("select words,word from sensors, LATERAL TABLE(splitFunction(words))").execute().print();

    }

    @FunctionHint(output = @DataTypeHint("ROW<word STRING>"))
    public static class SplitFunction extends TableFunction<Row>{
        public void eval(String value){
            String[] split = value.split(" ");
            for (String s : split) {
                collect(Row.of(s));
            }
        }
    }
}
